package demo2;

import java.io.*;
import java.net.*;

public class MyServer {

    public static Shape test(String[] s){
        if (s[0].equals("rectangle")) {
            System.out.printf("长:%s \t 宽:%s\n",s[1],s[2]);
            double l = Double.parseDouble(s[1]);
            double w = Double.parseDouble(s[2]);
            return new Rectangle(w ,l);
        } else if (s[0].equals("triangle")) {
            System.out.printf("第一条边:%s \t 第二条边:%s \t 第三条边:%s\n",s[1],s[2],s[3]);
            double a = Double.parseDouble(s[1]);
            double b = Double.parseDouble(s[2]);
            double c = Double.parseDouble(s[3]);
            if(new Triangle().isRightTriangle(a,b,c)){

            }
            return new Triangle(a,b,c);
        } else {
            System.out.printf("半径是:%s\n",s[1]);
            double r = Double.parseDouble(s[1]);
            return new Circle(r);
        }
    }

    public static void main(String[] args) {
        try{
            ServerSocket server = new ServerSocket(1680);
            Socket socket = server.accept();

            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));

            System.out.println("服务器已启动，等待客户端消息...");
            String s;
            while(( s = in.readLine()) != null){
                String[] string = s.split(" ");
                System.out.println("收到客户端求面积的图形是：" + string[0]);

                Shape shape = test(string);

                if("bye".equalsIgnoreCase(s)){
                    System.out.println("客户端请求关闭连接");
                    break;
                }

                double res = shape.getArea();
                String response = Double.toString(res);
                out.println(response);

                if ("bye".equalsIgnoreCase(response)) {
                    System.out.println("服务器主动关闭连接...");
                    break;
                }
            }

            System.out.println("连接正在关闭....");
            in.close();
            out.close();
            socket.close();
            server.close();
        } catch (Exception e) {
            throw new RuntimeException("服务器异常", e);
        }
    }
}


